//
//  SLEmotionPackage.swift
//  Emotion
//
//  Created by lirenqiang on 16/6/1.
//  Copyright © 2016年 lirenqiang. All rights reserved.
//

import UIKit

//每页显示的表情数据的个数
let EmoticonPageCount = 21

//表情的行数和列数
let EmoticonColCount = 7
let EmoticonRowCount = 3

class SLEmoticonPackage: NSObject {

    var title: String?
    
    var sectionEmoticon: [[SLEmoticon]] = [[SLEmoticon]]()
    
    init(id: String, title: String, array: [[String : String]]) {
        self.title = title
        super.init()
        
        var tempArray = [SLEmoticon]()
        
        //遍历字典, 字典转模型
        var index = 0
        
        for arrT in array {
            
            let emoticon = SLEmoticon(id: id, dict: arrT)
            
            //添加到数组中
            tempArray.append(emoticon)
            
            index += 1
            //每隔20个表情添加一个删除的模型
            if index == 20 {
                //添加一个删除的模型
                let delete = SLEmoticon(isDelete: true)
                //添加到数组中
                tempArray.append(delete)
                
                //重置index
                index = 0
            }
        }
        
        //操作删除模型的数据完毕后, 就应该看每组的最后一页能够装满21个表情
        //如果不能装满21个表情 添加空白表情
        let delta = tempArray.count % 21
        
        if delta != 0 {
            //前20个,添加空白
            for _ in delta..<20 {
                let space = SLEmoticon(isEmpty: true)
                tempArray.append(space)
            }
            
            //最后一个添加一个删除的模型
            //添加一个删除的模型
            let delete = SLEmoticon(isDelete: true)
            tempArray.append(delete)

        }
        
               
        
        //转换为二维数组
        sectionEmoticon = sectionEmoticons(tempArray)
    }
    
    private func sectionEmoticons(array: [SLEmoticon]) -> [[SLEmoticon]]{
        
        //计算页数
        let pageCount = (array.count - 1) / EmoticonPageCount + 1
        
        var tempArray = [[SLEmoticon]]()
        
        var length = EmoticonPageCount
        
        for i in 0..<pageCount {
            
            let loc = i * EmoticonPageCount
            
            if loc + length > array.count {
                length = array.count - loc
            }
            
            let range = NSMakeRange(loc, length)
            let subArray = (array as NSArray) .subarrayWithRange(range) as! [SLEmoticon]
            
            tempArray.append(subArray)
        }
        
        return tempArray
    }
    
}
